<template>
	<div class="qualityEvaluationMini" v-loading="loading">
		<div class="qualityAnalysisSearch">
			<div class="mindRadioGroup">
				<span class="mindRadio" v-for="item in timeSearchList" :key="item.value" :class="{ active: item.value === qualityAnalysisSearch }" @click="qualityAnalysisChange(item.value)">{{item.label}}</span>
			</div>
			<timePickerMini :range="qualityAnalysisSearch" :change="qualityAnalysisChange" />
		</div>
		<div class="evaluation">
			<!-- <h2 class="title">水环境质量评价</h2> -->
			<div class="evaluationCard">
				<div class="cardTit">
					<span>水质达标情况分析</span>
				</div>
				<div class="chartBox">
					<charts :option="qualityAnalysisChart" :clickEvent="qualityAnalysisClick"></charts>
				</div>
			</div>
			<div class="evaluationCard">
				<div class="cardTit">
					<span>超标站点数</span>
				</div>
				<div class="chartBox">
					<charts :option="qualityExceedNumChart"></charts>
				</div>
			</div>
			<div class="evaluationCard">
				<div class="cardTit">
					<span>超标时段分析</span>
				</div>
				<div class="chartBox">
					<charts :option="exceedAnalysisLine"></charts>
				</div>
			</div>
		</div>


		<el-dialog custom-class="factorTable" :visible.sync="suspensionBoxFlag" width="90%" top="2vh" append-to-body>
			<el-dialog :title="curStation + ' ' + curFactor + factorTableType + '数据列表'" top="10vh" :visible.sync="factorTableVisible" append-to-body>
				<el-table :data="factorTable" stripe max-height="600" v-loading="factorTableLoading" style="margin-top: -20px;">
					<!-- <el-table-column prop="waterstation" label="水站" align="center"></el-table-column> -->
					<el-table-column prop="time" label="监测时间" align="center"></el-table-column>
					<el-table-column prop="value" label="监测值" align="center">
						<template slot-scope="{row}">
							<span :style="{color: factorTableType === '超标' ? (row.multiple > 0.15 ? '#e53139' : '#f59f4a') : '#606266' }">{{row.value}}</span>
						</template>
					</el-table-column>
					<el-table-column prop="value" label="超标倍数" align="center" v-if="factorTableType === '超标'">
						<template slot-scope="{row}">
							<span :style="{color: row.multiple > 0.15 ? '#e53139' : '#f59f4a' }">{{ row.multiple }}</span>
						</template>
					</el-table-column>
				</el-table>
			</el-dialog>
			<el-row class="analysisPieData card">
				<!-- 水质达标情况分析 饼图 -->
				<div class="cardTit">
					<p class="title">水质达标情况分析 <span style="margin-left: 12px;" v-loading="pieChartLoading" element-loading-custom-class="loadingText"></span></p>
				</div>
				<div class="cardCnt analysisPieDataCnt">
					<div class="chartCnt" v-for="(item, index) of pieOption" :key="index" v-show="item.show">
						<charts :option="item" :isShow="item.show" :clickEvent="analysisPieDataClick"></charts>
					</div>
				</div>
			</el-row>
			<el-row class="suspensionRow2">
				<div class="pollutionFactor card">
					<!-- 主要污染因子 -->
					<div class="cardTit">
						<p class="title">主要污染因子</p>
					</div>
					<div class="cardCnt pollutionFactorCnt">
						<div class="noData" v-show="Object.keys(pollFactorData).length <= 0">
							暂无
						</div>
						<div class="progressBox" v-show="Object.keys(pollFactorData).length > 0" v-for="(val, name) of pollFactorData" :key="name">
							<span class="proTit">{{name}}</span>
							<el-progress :show-text="false" :stroke-width="22" :percentage="parseFloat((val*100).toFixed(2))" style="width: 69%;float: left;backgroungd: red;"></el-progress>
							<span class="proVal">{{ (val*100).toFixed(2) }}%</span>
						</div>
					</div>
				</div>
				<div class="companyType card">
					<!-- 涉及企业类型 -->
					<div class="cardTit">
						<p class="title">涉及企业类型</p>
					</div>
					<div class="cardCnt companyTypeCnt">
						<el-table :data="companyTypeTable" border style="width: 80%;margin: 0 auto;box-shadow: 3px 3px 10px #dedede;" :header-cell-style="{color: '#666', backgroundColor: '#f6f6f6'}">
							<el-table-column prop="name" align="center" label="超标因子">
							</el-table-column>
							<el-table-column prop="sourceType" align="center" label="涉及企业类型">
								<template slot-scope="{row}">
									<span v-show="!row.sourceType.length">暂无</span>
									<span v-show="row.sourceType.length" v-for="(item, key) in row.sourceType" :key="key">
										{{item}}
									</span>
								</template>
							</el-table-column>
						</el-table>
					</div>
				</div>
			</el-row>
		</el-dialog>
	</div>
</template>

<script>
	import {
		mapGetters,
		mapActions
	} from "vuex"
	import charts from '../components/charts.vue'
	import timePickerMini from '../components/timePickerMini.vue'
	import common from "../plugins/common.js";
	import standard from "../plugins/standard.js";
	export default {
		name: "qualityEvaluationMini",
		props: ['isShow'],
		components: {
			charts,
			timePickerMini
		},
		data() {
			return {
				loading: false,
				qualityAnalysisSearch: "259200000",
				timeSearchList: [{
						label: "近三天",
						value: "259200000"
					},
					{
						label: "近一周",
						value: "604800000"
					},
					{
						label: "近一个月",
						value: "2592000000"
					},
				],
				qualityAnalysisChart: {}, //水环境质量排名 - 达标率超标率对比
				qualityExceedNumChart: {}, //水环境质量排名 - 超标站点数
				exceedAnalysisLine: {}, //水环境质量排名 - 超标时段分析

				pieChartLoading: false,
				suspensionBoxFlag: false,
				pieOption: {
					ph: {},
					ammoniaNitrogen: {},
					nitrogen: {},
					phosphorus: {},
					cuprum: {},
					nickel: {},
					chromium: {},
					prussiate: {},
					cod: {}
				},
				pieDefault: {
					/**
					 * 需要动态配置的选项
					 * 
					 * title.text
					 * series[0].name
					 * series[0].data
					 * 
					 */
					show: false,
					color: ['#ffb35f', '#5ddeb7'],
					title: {
						left: 'center',
						textStyle: {
							fontSize: 14,
						}
					},
					tooltip: {
						trigger: 'item',
						formatter: "{a} <br/>{b}: ({d}%)"
					},
					series: [{
						type: 'pie',
						radius: ['40%', '50%'],
						avoidLabelOverlap: false,
						label: {
							formatter: '{b}: \n{d}%'
						},
					}]
				},

				factorTableVisible: false,
				allFactorResult: [],
				factorTableLoading: false,
				factorTable: [],
				factorTableType: null,
				curFactor: null,
				curStation: null,

				standard,
				common,
			}
		},
		computed: {
			...mapGetters({
				qualityData: 'getQualityData',
				stationList: 'getStationList',
				rankAnalysis: 'getRankAnalysisChart',
				qualityExceedNum: 'getQualityExceedNum',
				qualityHasCod: "getQualityHasCod",
				quaEvaLine: 'getQuaEvaLine',
				analysisPieData: 'getAnalysisPieData',
				pollFactorData: 'getPollFactorData',
				companyTypeTable: 'getCompanyTypeTable',
				times: 'getTimes'
			})
		},
		methods: {
			...mapActions([
				'fetchQualityEvaluationChart',
				'fetchQualityEvaluationLine',
				'fetchQualityEvaDetailChart',
				'postQualityEvaDetailList'
			]),
			qualityAnalysisChange(val) { //水环境质量分析 时间段筛选变化
				this.qualityAnalysisSearch = val
				setTimeout(() => {
					this.postQualityAnalysis()
				})
			},
			async postQualityAnalysis() {
				this.loading = true
				let res = await this.fetchQualityEvaluationChart({
					startTime: this.times.startTime,
					endTime: this.times.endTime,
				})
				if (res) {
					this.$notify.warning({
						title: '提示',
						message: res,
						duration: 2000
					});
				} else {
					await this.fetchQualityEvaluationLine({
						starttime: this.times.startTime,
						lasttime: this.times.endTime,
					})
					this.configQualityAnalysisChart()
					this.configExceedNumChart()
					this.configLineChart()
				}
				this.loading = false
			},
			configQualityAnalysisChart() {
				let qualityData = this.qualityData
				this.qualityAnalysisChart = {
					color: ['#ff6341', '#2ac4e0'],
					grid: {
						top: 20,
						left: 40,
						right: 10,
						bottom: 80
					},
					tooltip: {
						trigger: 'axis',
						// formatter: '{b}<br />{a0}: {c0}%<br />{a1}: {c1}%',
						formatter: (params) => {
							let str = `${params[0].name}<br />`
							for (let i = 0; i < params.length; i++) {
								str +=
									`<span style="display:inline-block;vertical-align: middle;border-radius: 50%;width:12px;height:12px;background: ${params[i].color.colorStops[0].color};"></span> ${params[i].seriesName}: ${params[i].value} % <br />`
							}
							return str
						},
						axisPointer: { // 坐标轴指示器，坐标轴触发有效
							type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
						}
					},
					xAxis: [{
						type: 'category',
						data: qualityData.map(v => v.xAxis),
						axisTick: {
							show: false
						},
						axisLabel: {
							formatter: (value) => value.split("").join("\n")
						}
					}],
					yAxis: [{
						type: 'value',
						max: 100,
						axisLabel: {
							formatter: '{value}%'
						},
						axisTick: {
							show: false
						},
					}],
					series: [{
							name: '达标率',
							type: 'bar',
							barWidth: 10,
							stack: '1',
							data: qualityData.map(v => v.value !== null ? (100 - v.value * 100).toFixed(2) : 0.00),
							itemStyle: {
								normal: {
									color: new this.$echarts.graphic.LinearGradient(0, 1, 1, 0, [{
										offset: 0,
										color: "#26d4d7"
									}, {
										offset: 1,
										color: "#2eb4e9"
									}]),
								}
							}
						},
						{
							name: '超标率',
							type: 'bar',
							barWidth: 10,
							stack: '1',
							data: qualityData.map(v => (v.value * 100).toFixed(2)),
							itemStyle: {
								normal: {
									color: new this.$echarts.graphic.LinearGradient(0, 1, 1, 0, [{
										offset: 0,
										color: "#ff363c"
									}, {
										offset: 1,
										color: "#fd9345"
									}]),
								}
							}
						}
					]
				}
			},
			configExceedNumChart() {
				// 超标站点数 
				let qualityExceedNum = this.qualityExceedNum
				this.qualityExceedNumChart = {
					color: ['#feac40'],
					grid: {
						top: 40,
						left: 40,
						right: 10,
						bottom: 70
					},
					tooltip: {
						trigger: 'axis',
						axisPointer: { // 坐标轴指示器，坐标轴触发有效
							type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
						}
					},
					xAxis: [{
						type: 'category',
						axisTick: {
							show: false
						},
						axisLabel: {
							formatter: (value) => value.split("").join("\n")
						},
						data: qualityExceedNum.map(v => common.translate(v.xAxis))
					}],
					yAxis: [{
						name: "个",
						type: 'value',
						max: 8,
						axisTick: {
							show: false
						},
					}],
					series: [{
						name: '超标站点数',
						type: 'bar',
						barWidth: 10,
						data: qualityExceedNum.map(v => v.value)
					}]
				}
			},
			configLineChart() {
				let quaEvaLine = this.quaEvaLine
				this.exceedAnalysisLine = {
					color: ['#5feac8'],
					grid: {
						top: 40,
						left: 40,
						right: 10,
						bottom: 40
					},
					xAxis: {
						type: 'category',
						name: '时间',
						data: Object.keys(quaEvaLine).map(v => (v * 2) + ':00'),
						axisTick: {
							show: false,
						}
					},
					yAxis: {
						name: "次",
						type: 'value',
						minInterval: 1,
						axisTick: {
							show: false,
						}
					},
					tooltip: {
						trigger: 'axis',
						formatter: '{b}时: 超标{c}次',
						axisPointer: {
							type: 'shadow'
						}
					},
					series: [{
						data: Object.values(quaEvaLine),
						type: 'bar',
						barWidth: 10,
					}, ]
				}
			},
			async qualityAnalysisClick(params) {
				this.pieChartLoading = true
				this.suspensionBoxFlag = true
				const remind = await this.fetchQualityEvaDetailChart({
					starttime: this.times.startTime,
					lasttime: this.times.endTime,
					waterstation: params.name
				})
				if (typeof remind === "string") {
					this.suspensionBoxFlag = false
					return this.$notify({
						type: 'warning',
						title: '提示',
						message: remind,
					})
				}
				this.configAnalysisPieChart(params.name)
				this.pieChartLoading = false
			},
			configAnalysisPieChart(waterstation) {
				let analysisPieData = this.analysisPieData
				let pieOption = this.pieOption
				for (let v in pieOption) {
					pieOption[v] = JSON.parse(JSON.stringify(this.pieDefault))
				}

				for (let i = 0; i < analysisPieData.length; i++) {
					let curPie = this.pieOption[analysisPieData[i].enName]
					curPie.show = analysisPieData[i].num1 !== null && analysisPieData[i].num2 !== null
					curPie.title.text = analysisPieData[i].name
					curPie.series[0].name = analysisPieData[i].name
					curPie.series[0].data = [{
							waterstation: waterstation,
							value: analysisPieData[i].num1,
							name: '超标率',
						},
						{
							waterstation: waterstation,
							value: analysisPieData[i].num2,
							name: '达标率',
							itemStyle: {
								borderWidth: 3,
								borderColor: '#fff',
							}
						},
					]
					// if(analysisPieData[i].enName === "chromium") {
					//   curPie.show = this.qualityHasCod == 1 ? false : true
					// }
					// if(analysisPieData[i].enName === "cod") {
					//   curPie.show = this.qualityHasCod == 2 ? false : true
					// }
				}
			},
			async analysisPieDataClick(params) {
				this.factorTableVisible = true
				this.factorTableLoading = true

				const waterstation = params.data.waterstation
				/**
				 * 这里比较特殊 为了匹配上 水站简称 和 全称
				 * 如果水站简称长度大于4 则用前两位来匹配水站全称
				 * 反之水站简称长度小于4 则用整个简称来匹配水站全称
				 */
				this.curStation = this.stationList.find(v => v.includes(waterstation.length > 4 ? waterstation.slice(0, 2) :
					waterstation))
				this.curFactor = params.seriesName
				this.factorTableType = params.name.replace(/率/, "")

				this.factorTable = []
				let result = await this.postQualityEvaDetailList({
					starttime: this.times.startTime,
					lasttime: this.times.endTime,
					waterstation: this.curStation
				})
				let factor = common.translate(params.seriesName, "chinaToEng")
				factor = factor === "pH" ? "ph" : factor //fixed ph or pH
				const unit = params.seriesName !== 'pH' ? ' mg / L' : ''

				let factorList = result[factor + 'Map']
				if (this.factorTableType === "超标") {
					for (let i = 0; i < factorList.overStandard.length; i++) {
						this.factorTable.push({
							time: factorList.overStandard[i].gmtMonitor,
							waterstation: factorList.overStandard[i].waterstation,
							value: factorList.overStandard[i][factor] + unit,
							multiple: common.multiples(factorList.overStandard[i][factor], standard[factor])
						})
					}
				} else {
					for (let i = 0; i < factorList.upStandard.length; i++) {
						this.factorTable.push({
							time: factorList.upStandard[i].gmtMonitor,
							waterstation: factorList.upStandard[i].waterstation,
							value: factorList.upStandard[i][factor] + unit
						})
					}
				}


				this.allFactorResult = result
				this.factorTableLoading = false
			},
			factorIsExceed(standard, factorVal) {
				/**
				 * factorIsExceed
				 * 
				 * standard 标准值 Number | Object
				 * factorVal 因子值 Number
				 * 
				 * 函数用于判断因子是否超标
				 * 超标返回 true   没超标返回 false
				 */
				if (typeof standard === "object") {
					/** ph standard */
					return !(factorVal > standard.min && factorVal < standard.max)
				} else {
					return factorVal > standard
				}

			},
		},
		created() {
			this.qualityAnalysisChange(this.qualityAnalysisSearch);
		},
		watch: {
			isShow(newVal) {
				if (newVal) this.qualityAnalysisChange(this.qualityAnalysisSearch);
			},
			suspensionBoxFlag(newVal) {
				if (!newVal) {
					for (let i in this.pieOption) {
						this.pieOption[i].show = newVal
					}
				}
			}
		}
	}
</script>

<style scoped>
	.qualityEvaluationMini {}

	.evaluation {
		width: 100%;
		height: 100%;
	}

	.qualityEvaluationMini .title {
		line-height: 40px;
		font-size: 14px;
		color: #0063ed;
	}

	.qualityEvaluationMini .qualityAnalysisSearch {
		padding-bottom: 12px;
	}

	.qualityEvaluationMini .evaluationCard {
		padding: 8px 8px 0;
		margin-bottom: 8px;
		box-shadow: 1px 1px 5px 0px rgba(75, 75, 75, 0.2);
		background-color: #fff;
	}

	.evaluationCard .cardTit {
		position: relative;
		padding-left: 8px;
		font-size: 12px;
		line-height: 28px;
		color: #535353;
	}

	.evaluationCard .cardTit::before {
		content: '';
		position: absolute;
		width: 2px;
		height: 16px;
		background: #0063ed;
		top: 50%;
		margin-top: -8px;
		left: 0;
	}

	.evaluationCard .chartBox {
		width: 100%;
		height: 200px;
	}

	.mindRadioGroup {
		height: 28px;
		line-height: 28px;
	}

	.mindRadio {
		box-sizing: border-box;
		padding: 2px 10px;
		border: 1px solid;
		border-color: transparent;
		margin-right: 10px;
		border-radius: 12px;
		transition: .25s ease;
		cursor: pointer;
		font-size: 12px;
	}

	.mindRadio:hover {
		color: #54b1fd;
	}

	.mindRadio.active {
		color: #54b1fd;
		border-color: #54b1fd;
	}

	/* card */
	.card {
		/* margin-top: 15px; */
		/* padding: 0 20px 20px 20px; */
		padding-left: 20px;
		background: #fff;
	}

	.card .cardTit {
		position: relative;
		height: 60px;
		line-height: 60px;
		border-bottom: 1px solid #ececec;
		margin-bottom: 20px;
		padding-left: 15px;
	}

	.card .cardCnt {}

	.cardTit p::before {
		content: '';
		position: absolute;
		width: 5px;
		height: 20px;
		background: #2399ff;
		top: 50%;
		margin-top: -10px;
		left: 0;
	}

	.suspensionRow2 {
		display: flex;
		justify-content: space-between;
	}

	.suspensionRow2::before,
	.suspensionRow2::after {
		content: none;
	}

	.pollutionFactor {
		width: 40%;
		height: 300px;
		margin-right: 2%;
	}

	.pollutionFactorCnt {
		/* height: calc(100% - 60px); */
		padding: 34px 0;
	}

	.pollutionFactorCnt .progressBox {
		overflow: hidden;
		margin-bottom: 35px;
	}

	.progressBox>>>.el-progress-bar__inner {
		background-image: linear-gradient(90deg,
			#ffd2a8 0%,
			#ff5858 100%);
	}

	.pollutionFactorCnt .progressBox:last-child {
		margin-bottom: 0;
	}

	.pollutionFactorCnt .progressBox .proVal {
		float: left;
		text-align: center;
		width: 15%;
	}

	.pollutionFactorCnt .progressBox .proTit {
		float: left;
		width: 16%;
		text-align: left;
	}

	.companyType {
		width: 58%;
		height: 300px;
	}

	.companyType .companyTypeCnt {
		width: 100%;
	}

	/* row3 */
	.row3 {}

	.analysisPieData {
		/* padding: 0 20px 20px 20px; */
	}

	.analysisPieDataCnt {
		display: flex;
		flex-wrap: wrap;
		min-height: 300px;
	}

	.analysisPieDataCnt .chartCnt {
		width: 25%;
		height: 200px;
	}

	.timeInfo {
		font-size: 12px;
		color: #bfbfbf;
	}

	.noData {
		width: 100%;
		line-height: 60px;
		text-align: center;
		color: #909399;
	}
</style>
<style>
	.factorTable .el-dialog__body {
		padding-top: 0;
	}

	.factorTable .el-dialog__header {
		background-image: none;
		height: 20px;
		padding: 0;
	}

	.factorTable .el-dialog__headerbtn .el-dialog__close {
		color: #666;
	}

	.loadingText .el-loading-spinner .circular {
		height: 30px;
		width: 30px;
	}
</style>
